package com.doge.calcalbum.business.note

import androidx.lifecycle.MutableLiveData
import com.doge.calcalbum.core.base.LoadStatus
import com.doge.calcalbum.db.model.Note
import com.doge.calcalbum.db.model.NoteTitle
import com.doge.calcalbum.utils.db
import com.doge.calcalbum.utils.runInTransaction
import com.doge.calcalbum.utils.runOnIO
import com.doge.calcalbum.utils.runOnUI
import java.io.File

class NoteRepository() {
    val noteList = db.noteDao().query()
    val loading = MutableLiveData<LoadStatus>()
    fun insert(title: String, content: String) = runOnIO {
        runOnUI { loading.value = LoadStatus.LOADING }
        val output = File(Note.noteFileDir(), "${System.currentTimeMillis()}.txt")
            .also { if (!it.exists()) it.createNewFile() }
        NoteUtils.write(content, output)
        val note = Note(
            title = title,
            filePath = output.absolutePath,
            createTime = System.currentTimeMillis(),
        )
        runInTransaction {
            db.noteDao().insert(note)
            runOnUI {
                loading.value = LoadStatus.SUCCESS
                loading.value = LoadStatus.IDLE
            }
        }
    }

    fun update(noteId: Int, title: String, content: String) = runOnIO {
        val note = db.noteDao().queryById(noteId) ?: return@runOnIO
        runOnUI { loading.value = LoadStatus.LOADING }
        val output = File(note.filePath).also { if (!it.exists()) it.createNewFile() }
        NoteUtils.write(content, output)
        runInTransaction {
            db.noteDao().updateTitle(NoteTitle(noteId, title))
            runOnUI {
                loading.value = LoadStatus.SUCCESS
                loading.value = LoadStatus.IDLE
            }
        }
    }

    fun delete(entries: List<Note>) = runInTransaction {
        entries.forEach { db.noteDao().delete(it) }
    }
}